package ru.dadle8.service.impl.callback;

import org.springframework.stereotype.Service;
import org.telegram.telegrambots.meta.api.objects.CallbackQuery;
import org.telegram.telegrambots.meta.api.objects.Update;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
import ru.dadle8.model.bot.entity.MessageCallbackData;
import ru.dadle8.model.bot.entity.State;
import ru.dadle8.model.bot.type.CallbackAction;
import ru.dadle8.model.bot.type.CommandState;
import ru.dadle8.service.api.callback.CallbackExecutor;
import ru.dadle8.service.api.callback.CallbackService;
import ru.dadle8.service.impl.AbstractExecutorService;

import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class CallbackExecutorImpl extends AbstractExecutorService implements CallbackExecutor {
    private final Map<Integer, CallbackService> callbackServiceMap;

    CallbackExecutorImpl(List<CallbackService> callbackServices) {
        this.callbackServiceMap = callbackServices.stream()
                .collect(Collectors.toMap(CallbackService::getAction, Function.identity()));
    }

    @Override
    public void execute(Update update) throws TelegramApiException {
        CallbackQuery callbackQuery = update.getCallbackQuery();
        MessageCallbackData callbackData = getMessageHelper().getMessageCallbackData(callbackQuery);

        CallbackService callbackService = callbackServiceMap.get(callbackData.actionId());
        if (callbackService == null) {
            // in callbackdata should be callbackActionId too
            State currentState = getStorage().getCurrentState(callbackQuery.getMessage().getChatId());
            if (currentState != null) {
                if (currentState.commandState() == CommandState.GET_WORKOUT) {
                    callbackService = callbackServiceMap.get(CallbackAction.GET_WORKOUT.getAction());
                    if (callbackService != null) {
                        callbackService.execute(update);
                    }
                }
            }
        } else {
            callbackService.execute(update);
        }
    }
}
